<template>
  <div class="container">
    <!-- 固定导航 -->
    <van-nav-bar fixed left-arrow @click-left="$router.back()" title="小思同学"></van-nav-bar>

    <!-- 聊天主体区域 -->
    <div class="chat-list">
      <div v-for="(item,index) in list" :key="index">
        <!-- 左侧是机器人小思 -->
        <div class="chat-item left" v-if="item.name !== 'me'">
          <van-image fit="cover" round src="https://img.yzcdn.cn/vant/cat.jpeg" />
          <div class="chat-pao">{{item.msg}}</div>
        </div>

        <!-- 右侧是当前用户 -->
        <div class="chat-item right" v-else>
          <div class="chat-pao">{{item.msg}}</div>
          <van-image fit="cover" round :src="userAvatar" />
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="reply-container van-hairline--top">
      <van-field v-model="word" placeholder="说点什么..." @keyup.enter="sendFn">
        <template #button>  
          <span style="font-size:12px;color:#999" @click="sendFn" >提交</span>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  // 1
  import {io} from "socket.io-client";
  import {getToken} from '../../utils/token.js'
  export default {
    name: 'Chat',
    computed:{
      ...mapState(['userAvatar'])
    },
    data() {
      return {
        word: '', // 输入框的内容
        list: [ // 所有的聊天信息
          // 根据name判断,消息应该是出现在左侧还是右侧
          {
            name: 'xs',
            msg: 'hi,我是小思'
          },
          {
            name: 'me',
            msg: '我是编程小王子'
          }
        ],
        // 2
        socket: null,// 客户端与服务器端建立链接的socket对象 
      }
    },
    created() {
      // 3 建立 socket 链接  和axios没有任何关系
      this.socket = io("http://toutiao.itheima.net", {
        query: {
          token: getToken()
        },
        transports: ['websocket']
      });
      // 4 检测服务通道是否已经启动
      this.socket.on("connect", () => {
        console.log('启动了websocket'); 
      });
      // 5 监听后端返回的聊天消息对象
      this.socket.on("message", (obj) => {
        console.log(obj,'小思')
        // 立即组织相同字段对象放到数组里更新,不能将后台返回的整个objpush进去数组,因为有些字段不一样
        this.list.push({
          name: 'xs',
          msg: obj.msg
        })
      });
    },
    watch:{
      // 监听聊天对象发生变化时,让滚动条自动滑到最后一条
      list(){
        this.$nextTick(()=>{
          // 获取聊天数组内最后一个div
        let last = document.querySelector('.chat-list>div:last-child')
          // 滑到最后一条
          last.scrollIntoView({
            behavior:'smooth'
          })
        })
      }
    },
    methods: {
      // me - 发送聊天信息事件
      sendFn() { // 发送聊天信息
      if(this.word.trim().length === 0)return alert('空的')
        this.socket.emit("message",{
          msg: this.word,
          timestamp: new Date().getTime()
        })
        // 把me发送的消息显示到页面上
        this.list.push({
          name: 'me',
          msg: this.word,
        })
        // 清空输入框
        this.word = ''
      }
    },
    // 组件销毁前解绑 socket 对象,否则占用资源
    beforeDestroy() {
      this.socket.close()
      this.socket = null
    }
  }
</script>

<style lang="less" scoped>
  .container {
    height: 100%;
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    box-sizing: border-box;
    background: #fafafa;
    padding: 46px 0 50px 0;

    .chat-list {
      height: 100%;
      overflow-y: scroll;

      .chat-item {
        padding: 10px;

        .van-image {
          vertical-align: top;
          width: 40px;
          height: 40px;
        }

        .chat-pao {
          vertical-align: top;
          display: inline-block;
          min-width: 40px;
          max-width: 70%;
          min-height: 40px;
          line-height: 38px;
          border: 0.5px solid #c2d9ea;
          border-radius: 4px;
          position: relative;
          padding: 0 10px;
          background-color: #e0effb;
          word-break: break-all;
          font-size: 14px;
          color: #333;

          &::before {
            content: '';
            width: 10px;
            height: 10px;
            position: absolute;
            top: 12px;
            border-top: 0.5px solid #c2d9ea;
            border-right: 0.5px solid #c2d9ea;
            background: #e0effb;
          }
        }
      }
    }
  }

  .chat-item.right {
    text-align: right;

    .chat-pao {
      margin-left: 0;
      margin-right: 15px;

      &::before {
        right: -6px;
        transform: rotate(45deg);
      }
    }
  }

  .chat-item.left {
    text-align: left;

    .chat-pao {
      margin-left: 15px;
      margin-right: 0;

      &::before {
        left: -5px;
        transform: rotate(-135deg);
      }
    }
  }

  .reply-container {
    position: fixed;
    left: 0;
    bottom: 0;
    height: 44px;
    width: 100%;
    background: #f5f5f5;
    z-index: 9999;
  }
</style>
